package com.loe.ktui.util

import android.os.Bundle
import androidx.fragment.app.Fragment
import java.io.Serializable
import kotlin.reflect.KClass

open class KtFragItem
{
    private var args: Bundle? = null
    private var frag: Fragment? = null
    var id: String? = null
    private var fragClass: Class<out Fragment>? = null

    constructor(frag: Fragment, id: String? = null)
    {
        this.frag = frag
        this.id = id
        args = frag.arguments
    }

    constructor(fragClass: Class<out Fragment>, id: String? = null)
    {
        this.fragClass = fragClass
        this.id = id
    }

    constructor(fragClass: KClass<out Fragment>, id: String? = null)
    {
        this.fragClass = fragClass.java
        this.id = id
    }

    val fragment: Fragment get() = (frag ?: fragClass!!.newInstance()).apply { arguments = args }

    fun id(id: String): KtFragItem
    {
        this.id = id
        return this
    }

    fun addArg(key: String?, value: Int): KtFragItem
    {
        if (args == null)
        {
            args = Bundle()
        }
        args?.putInt(key, value)
        return this
    }

    fun addArg(key: String?, value: String?): KtFragItem
    {
        if (args == null)
        {
            args = Bundle()
        }
        args?.putString(key, value)
        return this
    }

    fun addArg(key: String?, value: Boolean): KtFragItem
    {
        if (args == null)
        {
            args = Bundle()
        }
        args?.putBoolean(key, value)
        return this
    }

    fun addArg(key: String?, value: Double): KtFragItem
    {
        if (args == null)
        {
            args = Bundle()
        }
        args?.putDouble(key, value)
        return this
    }

    fun addSerializableArg(key: String?, value: Serializable): KtFragItem
    {
        if (args == null)
        {
            args = Bundle()
        }
        args?.putSerializable(key, value)
        return this
    }
}